import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:test2/model/scene.dart';
import 'dart:io';

import 'package:audioplayers/audioplayers.dart';
import 'package:desktop_screenshot/desktop_screenshot.dart';
import 'package:flutter/foundation.dart';
import 'package:hive/hive.dart';
import 'package:image/image.dart' as Img;

import 'package:hotkey_manager/hotkey_manager.dart';
import 'package:flutter/services.dart';
import 'package:test2/base/base_page.dart';
import 'package:test2/style/style.dart';
import 'package:test2/util/bus.dart';
import 'package:test2/widget/image.dart';

import '../util/PicUtil.dart';
import '../util/hotkeyUtil.dart';
import '../util/platform.dart';
import '../util/sp.dart';
import '../util/widget.dart';

class SceneAdd extends StatefulWidget {
  const SceneAdd({super.key, required this.boxName, this.info});

  final String boxName;
  final SceneC? info;

  @override
  State<SceneAdd> createState() => _SceneAddState();
}

class _SceneAddState extends BaseState<SceneAdd> {
  final _desktopScreenshotPlugin = DesktopScreenshot();
  AudioPlayer audioPlayer = AudioPlayer();

  Uint8List? screenshot1;
  Uint8List? screenshot2;

  bool edit = false;
  late SceneC info;

  File? picLocation;
  File? picScene;

  int needScreenshot = -1;

  bool picLocationChanged = false;
  bool picSceneChanged = false;
  TextEditingController _textEditingController = TextEditingController();

  final HotKey _hotKey = HotKey(
    key: HotKeyUtil.getScreenShotKey(),
    modifiers: [HotKeyModifier.alt],
    // Set hotkey scope (default is HotKeyScope.system)
    scope: HotKeyScope.system, // Set as inapp-wide hotkey.
  );

  initHotkey() async {
    if (!PlatformUtil.isDesktop()) {
      return;
    }

    await hotKeyManager.register(
      _hotKey,
      keyDownHandler: (hotKey) {
        print('onKeyDown+${hotKey.toJson()}');
        takeScreenshot();
      },
      // Only works on macOS.
      keyUpHandler: (hotKey) {
        print('onKeyUp+${hotKey.toJson()}');
      },
    );
  }

  Future<void> takeScreenshot() async {
    if (!edit) {
      return;
    }
    // 如果指定了要截图，或者有一个图片没有被选择，则允许截图
    if (needScreenshot != -1 ||
        (screenshot1 == null && picLocation == null) ||
        (screenshot2 == null && picScene == null)) {
    } else {
      return;
    }
    Uint8List? screenShot;
    try {
      screenShot = await _desktopScreenshotPlugin.getScreenshot();
      await audioPlayer.stop();
      audioPlayer.play(AssetSource("mp3/ss.mp3"));
    } on PlatformException catch (e) {
      print('Failed to capture screenshot: ${e.message}');
    }

    if (kDebugMode) {
      print("ScreenShotSize ${screenShot?.lengthInBytes}");
    }

    if (!mounted) return;

    if (screenShot != null) {
      // int start = DateTime.now().millisecondsSinceEpoch;
      // var decodeImage2 = Img.decodeImage(screenShot);
      // print(DateTime.now().millisecondsSinceEpoch-start);
      // if (decodeImage2 != null) {
      //   double scaleW = decodeImage2.width / 1920;
      //   double scaleH = decodeImage2.height / 1080;
      //   double scale = min(scaleW, scaleH);
      //   if (scale < 1) {
      //     scale = 1;
      //   }
      //
      //   decodeImage2 = Img.resize(
      //     decodeImage2,
      //     width: (decodeImage2.width / scale).toInt(),
      //     height: (decodeImage2.height / scale).toInt(),
      //     maintainAspect: true,
      //   );
      //   print(DateTime.now().millisecondsSinceEpoch-start);
      //   // print("${decodeImage2.width}");
      //   screenShot = Img.encodeJpg(decodeImage2, quality: 85);
      //   print(DateTime.now().millisecondsSinceEpoch-start);
      // }

      screenShot = await FlutterImageCompress.compressWithList(
        screenShot,
        minWidth: 1920,
        minHeight: 1080,
        quality: 95,
      );
    }

    setState(() {
      // 优先指定截图
      if (needScreenshot != -1) {
        if (needScreenshot == 1) {
          screenshot1 = screenShot;
          picLocation = null;
          picLocationChanged = true;
        }

        if (needScreenshot == 2) {
          screenshot2 = screenShot;
          picScene = null;
          picSceneChanged = true;
        }

        needScreenshot = -1;
        return;
      }

      // 哪个图片没有就给哪个
      if (screenShot != null) {
        if (screenshot1 == null && picLocation == null) {
          screenshot1 = screenShot;
          picLocation = null;
          picLocationChanged = true;
          return;
        }

        if (screenshot2 == null && picScene == null) {
          screenshot2 = screenShot;
          picScene = null;
          picSceneChanged = true;
          return;
        }
      }
    });
  }

  @override
  void initState() {
    if (widget.info == null) {
      info = SceneC(
        tip: "",
        positionPic: "",
        scenePic: "",
        done: false,
        tag: "",
      );
      edit = true;
    } else {
      info = SceneC(
        tip: widget.info!.tip,
        positionPic: widget.info!.positionPic,
        scenePic: widget.info!.scenePic,
        done: widget.info!.done,
        tag: widget.info!.tag,
      );
    }
    _textEditingController.text = info.tip;
    if (widget.info?.key != null) {
      picLocation = File(PicUtil.picRootPath + info.positionPic);
      picScene = File(PicUtil.picRootPath + info.scenePic);
    }

    initHotkey();
    init();
    super.initState();
  }

  List<String> tags = ["无", ...defaultTags];

  init() async {
    tags.addAll(SpUtil.get().getStringList("tags") ?? []);
    setState(() {
      tags;
    });
  }

  @override
  void dispose() {
    if (PlatformUtil.isDesktop()) {
      hotKeyManager.unregister(_hotKey);
    }
    audioPlayer.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.info?.key == null ? "添加场景" : "修改场景"),
        actions: [
          if (!edit)
            IconButton(
              onPressed: () {
                setState(() {
                  edit = true;
                });
              },
              icon: Icon(Icons.edit),
            ),
        ],
      ),
      floatingActionButton: edit
          ? FloatingActionButton(
              onPressed: () {
                commit();
              },
              child: Icon(Icons.check),
            )
          : null,
      body: SizedBox.expand(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(16),
          child: Column(
            spacing: 16,
            children: [
              TextField(
                maxLines: null,
                keyboardType: TextInputType.multiline,
                readOnly: !edit,
                controller: _textEditingController,
                decoration: InputDecoration(labelText: "描述(选填)"),
                onChanged: (s) {
                  info.tip = s;
                },
              ),

              Row(
                children: [
                  BorderContainer(
                    radius: 30,
                    bgColor: Theme.of(context).primaryColorLight,
                    child: Padding(
                      padding: EdgeInsetsGeometry.symmetric(
                        vertical: 4,
                        horizontal: 12,
                      ),
                      child: Text(info.tag.isEmpty ? "无" : info.tag),
                    ),
                  ),
                  Spacer(),
                  if (edit)
                    DropdownButton<String>(
                      underline: SizedBox(),
                      hint: Text("标签选择"),
                      value: null,
                      onChanged: (String? newValue) {
                        setState(() {
                          String s = newValue ?? "";
                          if (s == "无") s = "";
                          info.tag = s;
                        });
                      },
                      items: tags.map<DropdownMenuItem<String>>((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                    ),
                ],
              ),

              if (edit)
                Text(
                  "tip: 按下快捷键会依次截屏填充没有图片的选项，如果需要指定图片更换，请点击图片下方截图按钮再截图",
                  style: TextStyle(fontSize: 12, color: Color(0xff999999)),
                ),

              ImagePickView(
                enable: edit,
                imageProvider: getImgProvider(picLocation, screenshot1),
                title: "位置",
                onPick: (file) {
                  setState(() {
                    picLocation = file;
                    screenshot1 = null;
                    picLocationChanged = true;
                  });
                },
                onScreenshot: () {
                  showToast("请按快捷键截图");
                  needScreenshot = 1;
                },
              ),

              // SizedBox(height: 4),
              ImagePickView(
                enable: edit,
                imageProvider: getImgProvider(picScene, screenshot2),
                title: "场景",
                onPick: (file) {
                  setState(() {
                    picScene = file;
                    screenshot2 = null;
                    picSceneChanged = true;
                  });
                },
                onScreenshot: () {
                  showToast("请按快捷键截图");
                  needScreenshot = 2;
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  ImageProvider? getImgProvider(File? file, Uint8List? screenshot) {
    if (file != null && screenshot != null) {
      throw Exception("file && screenshot exist!");
    }

    if (file != null) {
      file.readAsBytes();
      return FileImage(file);
    }
    if (screenshot != null) {
      return MemoryImage(screenshot);
    }

    return null;
  }

  void commit() async {
    // if (info.tip.isEmpty) {
    //   showToast("请输入游戏名");
    //   return;
    // }

    if (picLocation == null && screenshot1 == null) {
      showToast("请选择位置");
      return;
    }

    if (picScene == null && screenshot2 == null) {
      showToast("请选择场景");
      return;
    }

    // 修改图片要删除旧的
    if (picLocationChanged) {
      // 删除旧图片
      if (widget.info?.key != null) {
        info.deletePicPos();
      }

      String picName = PicUtil.savePic(
        picLocation == null ? screenshot1 : picLocation!.readAsBytesSync(),
      );
      if (picName.isEmpty) {
        showToast("图片保存出错");
        return;
      }

      info.positionPic = picName;
    }

    // 修改图片要删除旧的
    if (picSceneChanged) {
      // 删除旧图片
      if (widget.info?.key != null) {
        info.deletePicScene();
      }

      String picName = PicUtil.savePic(
        picScene == null ? screenshot2 : picScene!.readAsBytesSync(),
      );
      if (picName.isEmpty) {
        showToast("图片保存出错");
        return;
      }

      info.scenePic = picName;
    }

    if (widget.info?.key == null) {
      Hive.box<SceneC>(widget.boxName).add(info);
    } else {
      Hive.box<SceneC>(widget.boxName).put(widget.info?.key, info);
    }

    bus.emit(EventType.scene);

    finish();
  }
}
